package top.yohann.study.common.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.yohann.study.common.common.GlobalException;
import top.yohann.study.common.dto.MailDto;

import javax.mail.internet.MimeMessage;

/**
 * @author Yeung Wah
 * @since 2021/11/21
 */
@Service
public class MailService extends BaseService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String senderEmail;

    @Value("${mail.default.subject}")
    private String defaultSubject;

    @Value("${mail.default.template}")
    private String defaultTemplate;

    @Value("${mail.default.placeholder}")
    private String placeholder;

    public boolean sendMail(MailDto mailDto) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            messageHelper.setFrom(senderEmail);
            messageHelper.setTo(mailDto.getMail());
            messageHelper.setSubject(mailDto.getSubject());
            messageHelper.setText(mailDto.getContent(), mailDto.isHtml());
            mailSender.send(message);
        } catch (Exception e) {
            GlobalException.throwOut("发送邮件失败:" + e.getMessage(), e);
        }

        return Boolean.TRUE;
    }

    public boolean sendCode(MailDto mailDto) {
        if (StringUtils.isEmpty(mailDto.getMail())) {
            GlobalException.throwOut("请正确填写邮箱");
        }

        if (StringUtils.isEmpty(mailDto.getSubject())) {
            mailDto.setSubject(defaultSubject);
        }

        String content = mailDto.getContent();
        if (StringUtils.isEmpty(content)) {
            content = defaultTemplate;
        }
        String code = this.generateCode();
        content = content.replace(placeholder, code);
        mailDto.setContent(content);

        boolean send = this.sendMail(mailDto);
        if (send) {
            this.setCode(mailDto.getMail(), code);
        }

        return send;
    }
}